const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
const xlsx = require('node-xlsx');
let {
  FormatData
} = require('./util.js');
cloud.init({
  env: "garbage-classify-9fw9us07bea7142"
})
let db = cloud.database()
const _ = db.command
const $ = db.command.aggregate
const MAXANSWER = 10
const MAX_LIMIT = 100
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    APPID,
    OPENID
  } = wxContext
  const app = new TcbRouter({
    event
  })

  //添加搜索历史
  app.router('addHot', async (ctx, next) => {
    let {
      hot_text,
    } = event
    let hot = db.collection('hot')
    let {
      total
    } = await hot.where({
      hot_text: hot_text
    }).count()
    if (total) {
      await hot.where({
          hot_text: hot_text
        })
        .update({
          data: {
            hot_num: _.inc(1)
          }
        })
    } else {
      await hot.add({
        data: {
          hot_text: hot_text,
          hot_time: new Date(),
          hot_num: 1
        }
      })
    }

    ctx.body = {
      code: 1,
      msg: "添加成功"
    }
  })

  //获取热点搜索
  app.router('getHot', async (ctx, next) => {
    let hot = db.collection('hot')
    let {
      data
    } = await hot.orderBy('hot_num', 'desc').limit(10).get()
    ctx.body = {
      code: 1,
      data
    }
  })

  //用户登录
  app.router('login', async (ctx, next) => {
    let {
      userInfo
    } = event
    let user = db.collection('user')
    let {
      total
    } = await user.where({
      OPENID: OPENID
    }).count()
    if (!total) {
      await user.add({
        data: {
          nickName: userInfo.nickName,
          gender: userInfo.gender,
          avatarUrl: userInfo.avatarUrl,
          OPENID: OPENID,
          isAdmin:false
        }
      })
    }
    let {
      data
    } = await user.where({
      OPENID: OPENID
    }).get()
    ctx.body = {
      code: 1,
      msg: "添加成功",
      userInfo: data[0]
    }
  })

  //获取个人信息
  app.router('getUserInfo', async (ctx, next) => {
    let user = db.collection('user')
    let {
      data
    } = await user.where({
      OPENID: OPENID
    }).get()
    ctx.body = {
      code: 1,
      userInfo: data[0]
    }
  })

  //修改用户信息
  app.router('setUserInfo', async (ctx, next) => {
    let {
      avatarUrl,
      nickName
    } = event
    let user = db.collection('user')
    await user.where({
      OPENID: OPENID
    }).update({
      data: {
        avatarUrl,
        nickName
      }
    })
    ctx.body = {
      code: 1
    }
  })

  //获取新闻
  app.router('getCommlist', async (ctx, next) => {
    let {
      page,
      limit
    } = event
    let comm = db.collection('comm')
    let {
      data
    } = await comm.skip((page - 1) * limit)
      .limit(limit).get()
    ctx.body = {
      code: 1,
      data: FormatData(data, {
        date: "date"
      })
    }
  })

  //获取新闻详情
  app.router("getCommInfo", async (ctx, next) => {
    let {
      commId,
      isLogin
    } = event
    let comm = db.collection('comm')
    let like = db.collection('like')
    let {
      data
    } = await comm.doc(commId).get()
    await comm.where({
      _id: commId
    }).update({
      data: {
        readNum: _.inc(1)
      }
    })
    data.isLike = false
    if (isLogin) {
      let {
        total
      } = await like.where({
        OPENID: OPENID,
        commId: commId
      }).count()
      if (total) {
        data.isLike = true
      } else {
        data.isLike = false
      }
    }
    ctx.body = {
      code: 1,
      data: FormatData(data, {
        date: "date"
      })
    }
  })

  //用户点赞
  app.router("addLike", async (ctx, next) => {
    let {
      commId
    } = event;
    let like = db.collection('like')
    let comm = db.collection('comm')
    let {
      total
    } = await like.where({
      OPENID: OPENID,
      commId: commId
    }).count()
    if (total) {
      await like.where({
        OPENID: OPENID,
        commId: commId
      }).remove()
      await comm.where({
        _id: commId
      }).update({
        data: {
          likeNum: _.inc(-1)
        }
      })
      ctx.body = {
        code: 2,
        data: "取消点赞成功"
      }
    } else {
      await like.add({
        data: {
          commId: commId,
          OPENID: OPENID
        }
      })
      await comm.where({
        _id: commId
      }).update({
        data: {
          likeNum: _.inc(1)
        }
      })
      ctx.body = {
        code: 1,
        data: "点赞成功"
      }
    }
  })


  //获取点赞新闻
  app.router('getCommlistByLike', async (ctx, next) => {
    let {
      page,
      limit
    } = event

    let {
      list
    } = await db.collection('like').aggregate()
      .lookup({
        from: "comm",
        localField: 'commId',
        foreignField: '_id',
        as: 'uapproval'
      }).match({
        OPENID: OPENID
      }).replaceRoot({
        newRoot: $.arrayElemAt(['$uapproval', 0])
      }).skip((page - 1) * limit)
      .limit(limit).end()


    ctx.body = {
      code: 1,
      data: FormatData(list, {
        date: "date"
      })
    }
  })

  //添加新闻
  app.router('addComm', async (ctx, next) => {
    let {
      tag,
      imgList,
      title,
      content
    } = event
    let comm = db.collection('comm')
    await comm.add({
      data: {
        tag,
        imgList,
        title,
        content,
        likeNum: 0,
        readNum: 0,
        date: new Date()
      }
    })
    ctx.body = {
      code: 1,
      data: "添加成功"
    }
  })

  /**
   * 分享他人，他人进入小程序
   */
  app.router('shareOther', async (ctx, next) => {
    let user = db.collection('user')
    let share = db.collection('share')
    let {
      otherOPENID
    } = event
    let {
      total
    } = await user.where({
      OPENID: OPENID
    }).count()
    if (total) {
      ctx.body = {
        code: 2,
        msg: "用户已注册"
      }
    } else {
      await share.add({
        data: {
          OPENID: OPENID,
          otherOPENID: otherOPENID,
          time: new Date()
        }
      })
      ctx.body = {
        code: 1,
        msg: "分享成功"
      }
    }
  })
  /**
   * 后台代码
   */
  //获取用户列表
  app.router('getUserlist', async (ctx, next) => {
    let {
      page,
      limit
    } = event
    let goods = db.collection('user')
    let {
      data
    } = await goods.skip((page - 1) * limit)
      .limit(limit).get()
    ctx.body = {
      code: 1,
      data: data
    }
  })

  //获取新闻列表
  app.router('getCommAdminlist', async (ctx, next) => {
    let {
      page,
      limit
    } = event
    let comm = db.collection('comm')
    let {
      data
    } = await comm.skip((page - 1) * limit)
      .limit(limit).get()
    data.forEach(item => item.img = item.imgList[0] || '')

    ctx.body = {
      code: 1,
      data: FormatData(data, {
        date: "date"
      })
    }
  })

  //删除新闻
  app.router('delCommAdmin', async (ctx, next) => {
    let {
      _id
    } = event
    let comm = db.collection('comm')
    let like = db.collection('like')
    await like.where({
      commId: _id
    }).remove()
    await comm.where({
      _id: _id
    }).remove()

    ctx.body = {
      code: 1,
      msg: "删除成功",
      data: ''
    }
  })

  //获取新闻详情
  app.router("getCommAdminById", async (ctx, next) => {
    let {
      commId
    } = event
    let comm = db.collection('comm')

    let {
      data
    } = await comm.doc(commId).get()

    ctx.body = {
      code: 1,
      data: FormatData(data, {
        date: "date"
      })
    }
  })

  //修改新闻
  app.router('updataCommAdmin', async (ctx, next) => {
    let {
      commId,
      tag,
      imgList,
      title,
      content
    } = event
    let comm = db.collection('comm')

    await comm.where({
      _id: commId
    }).update({
      data: {
        tag,
        imgList,
        title,
        content
      }
    })

    ctx.body = {
      code: 1,
      msg: "修改成功",
      data: ''
    }
  })


  return app.serve();
}